import * as fs from "fs";
import { getStat, getCurrentDirPath, isExistPath } from "../utils/fs";
import { success, fail, ProxyMode } from "../utils/base";

export default defineEventHandler(async (event) => {
  // 获取请求参数
  const body = await readBody(event);
  // console.log("获取请求参数：", body);
  const { writePath, filePath } = getCurrentDirPath(
    "/public/log",
    "ignoreErrors.json"
  );
  // 获取单例
  const instance = ProxyMode();
  // 防止并发过大
  try {
    instance.asyncNums++;
    if (instance.asyncNums > 1) {
      return success(`服务器繁忙${instance.asyncNums}`);
    }
  } catch (error) {
    console.log("服务端并发过大,已拦截", error);
  }

  // 操作数据
  let isDir = await isExistPath(writePath);
  let isFile = await isExistPath(filePath!);
  /********* 文件保存出错的时候:需要删除文件 end *******/
  const time = formatDate(new Date());
  if (isDir && isFile) {
    if (body && body != "undefined" && typeof body == "object") {
      // 1. 读取现有的 JSON 文件
      const jsonString = fs.readFileSync(filePath!, "utf8");
      const fileData = JSON.parse(jsonString);
      // 是否删除之前的记录
      if (body.recordId) {
        try {
          fileData.list = fileData.list.filter(
            (e: any) => e.data.recordId != body.recordId
          );
          // 将更新后的对象写回文件
          const newJsonString = JSON.stringify(fileData, null, 2);
          fs.writeFileSync(filePath!, newJsonString, "utf8");
          return success("删除成功");
        } catch (error) {
          return fail({ msg: "删除失败", error });
        }
      }
      // 添加记录
      else if (body.text) {
        try {
          fileData.list.push({
            time,
            text: body.text,
          });
          // 将更新后的对象写回文件
          const newJsonString = JSON.stringify(fileData, null, 2);
          fs.writeFileSync(filePath!, newJsonString, "utf8");
          instance.ignoreErrors = []; // 下一次回重新读取,过滤信息到缓存中
          return success("添加成功");
        } catch (error) {
          return fail({ msg: "添加失败", error });
        }
      }
    }
    // 获取列表
    else {
      // 1. 内存中有就不用再读取文件了
      if (instance.ignoreErrors.length > 0)
        return success(instance.ignoreErrors);
      // 2. 读取现有的 JSON 文件
      const jsonString = fs.readFileSync(filePath!, "utf8");
      const fileData = JSON.parse(jsonString);
      instance.ignoreErrors = fileData.list.map((e: any) => e.text);
      instance.ignoreErrors.push("Script error."); // 增加一条默认记录,防止频繁读取一个空数组
      instance.ignoreErrors.push("10018413923"); // berry
      instance.ignoreErrors.push("10015279372"); // jerry
      instance.ignoreErrors.push("10017996619"); // allen
      instance.ignoreErrors.push("10019688381"); // Camellia
      instance.ignoreErrors.push("10018274942"); // morgan
      return success(instance.ignoreErrors);
    }
  }
  // 不存在
  else {
    const isCreate = createDirectorySync(writePath);
    if (isCreate) {
      const writeDate: any = {
        create: time,
        list: [],
      };
      if (body && body.text) {
        writeDate.list.push({
          time,
          text: body.text,
        });
      }

      const isOK = await creatContentToPathSync(
        filePath!,
        JSON.stringify(writeDate, null, 2)
      );
      if (isOK === true) {
        return success("添加成功");
      } else {
        return fail("添加失败");
      }
    } else {
      return fail("目录创建失败");
    }
  }
});
